package com.example.demo.config.security.login.usernamepassword;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 *
 * DaoAuthenticationProvider.issupport()发法会验证当前认证操作是通过用户名密码验证的
 *
 * 添加验证码校验的一种方式
 * 校验 验证码的AuthenticationProvider
 * DaoAuthenticationProvider是专门校验账号密码的
 * KaptchaAuthenticationProvider专门校验验证码
 * 将来两个顺序，先执行验证码校验KaptchaAuthenticationProvider后执行DaoAuthenticationProvider
 *
 */
public class KaptchaAuthenticationProvider extends DaoAuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //用户输入的验证码
        String vcode = request.getParameter("vcode");
        //  接口“/vc.jpg”将验证码放入session了
        String kaptcha= (String)request.getSession().getAttribute("kaptcha");
        if (!vcode.equals(kaptcha)) {
            //可以自定义异样
            throw new RuntimeException("验证码输入错误");
        }
        return super.authenticate(authentication);
    }
}
